import logging
import os
from logging.handlers import RotatingFileHandler
from colorlog import ColoredFormatter
from datetime import datetime


# 控制台日志处理器
def create_log_console_handler():
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    # 设置日志输出格式和颜色
    log_format = "%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    color_format = ColoredFormatter(
        log_format,
        log_colors={
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red',
        }
    )
    console_handler.setFormatter(color_format)
    return console_handler


# 文件日志处理器
def create_file_handler():
    # 创建日志目录
    log_dir = 'logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 生成每日日志文件名
    date_str = datetime.now().strftime('%Y%m%d')
    log_filename = f'{log_dir}/{date_str}.log'
    
    # 创建一个handler，每个文件最大512KB
    file_handler = RotatingFileHandler(filename=log_filename,
                                       backupCount=10,
                                       maxBytes=12 * 1024,
                                       encoding='utf-8')
    # 设置日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    return file_handler


# 怎么才能同时打印日志文件，还能输出控制台呢？用handler处理器
handler_c = create_log_console_handler()
handler_f = create_file_handler()
tortoiseLogger = logging.getLogger('tortoise')
# tortoise需要打印出SQL 故设置成DEBUG
tortoiseLogger.level = logging.DEBUG
tortoiseLogger.addHandler(handler_c)
tortoiseLogger.addHandler(handler_f)
# 自己项目的logger，也要输出到控制台 还有文件
blogLogger = logging.getLogger('blog')
blogLogger.level = logging.DEBUG
blogLogger.addHandler(handler_c)
blogLogger.addHandler(handler_f)
